package com.fz.study.project.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fz.study.project.entity.Result;
import com.fz.study.project.entity.ShopType;
import com.fz.study.project.exception.BizException;
import com.fz.study.project.mapper.TbShopTypeMapper;
import com.fz.study.project.service.ITbShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import static com.fz.study.project.utils.RedisConstants.SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-26
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<TbShopTypeMapper, ShopType> implements ITbShopTypeService {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Object queryTypeList() {
//        先从redis中查找
        String map = stringRedisTemplate.opsForValue().get(SHOP_TYPE_KEY);
        if (StrUtil.isNotBlank(map)) {
            return Result.success(JSONUtil.toList(map, ShopType.class));
        }
//        再从数据库中查找
        List<ShopType> list = list();
        if (Objects.isNull(list)){
            BizException.throwBizException("商品类型查询失败");
        }
//        将查询到的数据存储到redis集合中
        stringRedisTemplate.opsForValue().set(SHOP_TYPE_KEY,JSONUtil.toJsonStr(list));
        return list;
    }
}
